class Article < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 10

  belongs_to :discipline
  belongs_to :user
  has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at ASC'
  has_one :document, :as => :attachable, :dependent => :destroy, :order => 'created_at DESC'
  has_many :document_versions, :class_name => 'Document', :as => :attachable, :dependent => :destroy, :order => 'created_at DESC'
  has_many :reviews, :dependent => :destroy, :order => 'created_at ASC'

  validates_presence_of :title, :body, :user, :discipline, :document

  before_create :set_default_replied_at

  def self.find_all_recent(limit = 10)
    find(:all, :order => 'created_at DESC', :limit => limit)
  end

  def self.build_search(term)
    term = "%#{term}%"
    where = self.find_where_options :inner => { :article => :or, :discussion => :or } do |p|
      p.title.downcase =~ term
      p.body.downcase  =~ term
    end
    where[:conditions]
  end

  protected

  def set_default_replied_at
    self.replied_at = Time.now
  end

end
